package md.NJavaBase;

import android.util.Log;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

//开屏广告管理器
public class SplashAdMgr {

    final String Tag;

    static SplashAdMgr m_I = null;
    public static SplashAdMgr I(){
        if(m_I!=null) return m_I;
        m_I = new SplashAdMgr("SplashAdMgr" );
        return m_I;
    }


    public SplashAdMgr(String tag)
    {
        Tag = tag;
    }

    //注册一个广告
    public void RegAD(ISplashAd ad)
    {
        mAdList.add(ad);
    }

    //在所有广告注册完毕后，管理器可以开始工作了
    public  void go(IAdLoaderCallback callback)
    {
        m_callback = callback;
    }

    public void show(int channel)
    {
        if(mAdList.size()==0)
        {
            Log.d(Tag,"没有注册开屏广告");
            m_callback.onError("Frequent");//频繁加载
            return;//没有找到处于空闲状态的loader
        }

        Log.d(Tag,"Loader开始工作");
        ISplashAd ad = mAdList.get((int) (Math.random()*mAdList.size()));
        mHasReward = false;
        ad.show(new IAdCallback() {
            @Override
            public void onLoad() {
                class callbackRunnable implements Runnable
                {
                    @Override public void run() {
                        m_callback.onLoad();
                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  callbackRunnable( ));
            }

            @Override
            public void onReward() {
                mHasReward = true;
            }

            @Override
            public void onClose() {
                class callbackRunnable implements Runnable
                {
                    @Override public void run() {
                        m_callback.onClose(mHasReward);
                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  callbackRunnable( ));

            }

            @Override
            public void onError(String errCode) {
                class callbackRunnable implements Runnable
                {
                    @Override public void run() {
                        m_callback.onError(errCode);
                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  callbackRunnable( ));

            }
        });
    }


    IAdLoaderCallback m_callback;
    ArrayList<ISplashAd> mAdList = new ArrayList<ISplashAd>();
    boolean mHasReward = false;
}
